
const gulp = require('gulp')
const cssmin = require('gulp-cssmin')
const sass = require('gulp-sass')(require('sass'))
const uglify = require('gulp-uglify')
const babel = require('gulp-babel')
const htmlmin = require('gulp-htmlmin')
const clean = require('gulp-clean')
const webserver = require('gulp-webserver')

//创建一个任务
gulp.task('test', function () {
    console.log('我的第一个gulp任务！')
})

//复制文件的任务
//pipe：将数据流串联
gulp.task('copy', function () {
    return gulp.src('./src/js/*.js') //文件读取为数据流
            .pipe(gulp.dest('./dist')) //数据流斜日文件
})

//打包css文件
gulp.task('css',function(){
    return gulp.src('./src/css/*.css')
            .pipe(cssmin())
            .pipe(gulp.dest('./dist/css/'))
})

//打包sass文件
gulp.task('sass',function(){
    return gulp.src('./src/sass/**')
            .pipe(sass())
            .pipe(cssmin())
            .pipe(gulp.dest('./dist/css'))
})

//打包js文件
//先压缩
gulp.task('js',function(){
    return gulp.src('./src/js/**')
            .pipe(babel({
                presets:['es2015']
            }))
            .pipe(uglify())
            .pipe(gulp.dest('./dist/js/'))
})
//es6转为es5


//打包html文件
gulp.task('pages',function(){
    return gulp.src('./src/pages/**')
            .pipe(htmlmin({
                removeEmptyAttributes:true, //移出所有空属性
                collapseWhitespace:true //压缩html
            }))
            .pipe(gulp.dest('./dist/pages'))
})

//处理static和lib文件，实际上就是直接复制
gulp.task('lib',function(){
    return gulp.src('./src/lib/**')
            .pipe(gulp.dest('./dist/lib'))
})

gulp.task('static',function(){
    return gulp.src('./src/static/**')
            .pipe(gulp.dest('./dist/static'))
})

//按顺序批量执行任务
// exports.default = gulp.series('sass','css','js','html','lib','static')
//同时批量执行任务
// exports.default = gulp.parallel('sass','css','js','html','lib','static')

//清除dist文件夹
gulp.task('clean',function(){
    return gulp.src('./dist',{allowEmpty:true}).pipe(clean())
})

//自动打开浏览器
gulp.task('webserver',function(){
    return gulp.src('./dist')
            .pipe(webserver({
                host:'localhost',
                port:3000,
                livereload:true,
                open:'./pages/index.html'
            }))
})

//自动监听


gulp.task('mywatch',function(){
    gulp.watch('./src/css/**',gulp.parallel('css'))
    gulp.watch('./src/sass/**',gulp.parallel('sass'))
    gulp.watch('./src/js/**',gulp.parallel('js'))
    gulp.watch('./src/pages/**',gulp.parallel('pages'))
    gulp.watch('./src/lib/**',gulp.parallel('lib'))
    gulp.watch('./src/static/**',gulp.parallel('static'))
})

exports.default = gulp.series('clean',gulp.parallel('sass','css','js','pages','lib','static'),gulp.series('webserver','mywatch'))